package com.liwei.lwmail.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.liwei.common.constant.AuthServerConstant;
import com.liwei.common.exception.BizCodeEnume;
import com.liwei.common.utils.R;
import com.liwei.common.vo.MemberResponseVo;
import com.liwei.lwmail.auth.feign.MemberFeignService;
import com.liwei.lwmail.auth.feign.ThirdPartyFeignService;
import com.liwei.lwmail.auth.vo.UserLoginVo;
import com.liwei.lwmail.auth.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Controller
public class LoginController {

    @Autowired
    private ThirdPartyFeignService thirdPartyFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 获取短信验证码
     * @param phone_number
     * @return
     */
    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone_number") String phone_number){

        //TODO 接口防刷

        //防止同一个手机号60s内再次发送验证码
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone_number);
        if (!StringUtils.isEmpty(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if(System.currentTimeMillis() - l < 60000){
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(),BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        //验证码的校验 redis key:SMS_CODE_CACHE_PREFIX:phone_number value:code
        String code = UUID.randomUUID().toString().substring(0, 5);
        String s = code+"_"+System.currentTimeMillis();
        String time = "2";
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone_number, s, Long.parseLong(time), TimeUnit.MINUTES);

        String content = "code:"+code+",expire_at:"+time;
        thirdPartyFeignService.sendCode(phone_number,content);
        return R.ok();
    }

    /**
     * 注册
     * //TODO 重定向携带数据，利用session原理。分布式下有问题,跳转到啊下一个页面，取出数据后数据就会删掉
     */
    @PostMapping( "/reg")
    public String register(@Valid UserVo user, BindingResult result,
                           RedirectAttributes redirectAttributes){
        if (result.hasErrors()){
            Map<String,String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",errors);//数据取出后就删除
            //校验出错
            return "redirect:http://auth.lwmall.com/reg.html";
        }
        //调用远程服务注册
            //校验验证码
        String code = user.getCode();
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + user.getPhoneNumber());
        if (!StringUtils.isEmpty(s)){
            if (code.equals(s.split("_")[0])){
                //删除验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + user.getPhoneNumber());
                //验证码通过,调用远程服务
                R r = memberFeignService.register(user);
                if (r.getCode() == 0){
                    //成功
                    return "redirect:http://auth.lwmall.com/login.html";
                }else {
                    Map<String,String> errors = new HashMap<>();
                    errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.lwmall.com/reg.html";
                }
            }else {
                Map<String,String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.lwmall.com/reg.html";
            }
        }else {
            Map<String,String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.lwmall.com/reg.html";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        //远程服务登录
        R r = memberFeignService.login(vo);
        if (r.getCode() == 0){
            //成功
            MemberResponseVo memberResponseVo = r.getData("data", new TypeReference<MemberResponseVo>() {});
            session.setAttribute(AuthServerConstant.LOGING_USER,memberResponseVo);
            if (!StringUtils.isEmpty(vo.getOriginUrl())){
                return "redirect:"+vo.getOriginUrl();
            }
            return "redirect:http://lwmall.com";
        }
        Map<String,String> errors = new HashMap<>();
        errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
        redirectAttributes.addFlashAttribute("errors",errors);
        return "redirect:http://auth.lwmall.com/login.html";
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session,
                            @RequestParam(value = "originUrl",required = false)String originUrl,
                            Model model){
        Object attribute = session.getAttribute(AuthServerConstant.LOGING_USER);
        if (attribute == null){
            model.addAttribute("originUrl",originUrl);
            return "login";
        }
        return "redirect:http://lwmall.com";
    }
}
